package jp.co.cos.ittrick.channel.controller.inquiry;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.controller.validator.Validators;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class SendMailController extends Controller {

    @Override
    public Navigation run() throws Exception {

    	if (!isPost() || !validate()) {
            return forward("/inquiry/");
        }

    	Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();


    	String subject = asString("subject");
    	String name = asString("username");
    	String mail = user.getEmail();
    	String msgBody = asString("msg");

    	Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("it.trick.cos@gmail.com", "IT TRICK", "UTF-8"));
        msg.addRecipient(Message.RecipientType.TO,
                         new InternetAddress("it.trick.cos@gmail.com", "IT TRICK", "UTF-8"));
        ((MimeMessage)msg).setSubject(subject ,"UTF-8");

        // 本文
        msgBody = msgBody + "\r\n\r\n\r\n" + "氏名： " + name + "\r\n" + mail;
        msg.setText(msgBody);
        Transport.send(msg);

        requestScope("loginFlg", true);

        return redirect("/inquiry/");
    }


    private boolean validate() {
        Validators v = new Validators(request);
        v.add("subject", v.required());
        v.add("username", v.required());
        v.add("msg", v.required());

        return v.validate();
    }
}
